package cn.qf.shop.service.impl;


import cn.qf.shop.exceptions.ShopException;
import cn.qf.shop.mapper.TUserMapper;
import cn.qf.shop.pojo.entity.TUser;
import cn.qf.shop.pojo.qo.TUserQO;
import cn.qf.shop.service.LoginUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class LoginUserServiceImpl implements LoginUserService {
    private final Logger logger = LoggerFactory.getLogger(LoginUserServiceImpl.class);
    @Resource
    TUserMapper tUserMapper;

    public TUser register(TUser tUser) throws RuntimeException {

        TUser tUserqo=null;
        //BeanUtils.copyProperties(tUserQO,tUser);

        //现在这里做判断该用户名是否已经存在
         tUserqo=tUserMapper.selectByUserName(tUser.getUsername());
        if(tUserqo!=null){
            //该用户名已经存在
            throw new ShopException("该用户名已经存在");
        }

      int i = tUserMapper.insertTUser(tUser);

        //创建标准返回对象
        if (i!=0) {
            //查询插入失败  抛出异常
            throw  new ShopException("用户插入失败");

        }
        tUser=tUserMapper.selectByUserName(tUser.getUsername());
       return tUser;
    }

    /**
     * 后端管理员用于登录的方法
     *
     * */

    public TUser login(TUserQO user) throws RuntimeException {


        TUser dbUser = tUserMapper.selectByUserName(user.getUsername());

        //当用户名不存在的时候
        if(dbUser==null){
            //用户不存在
            throw new ShopException("用户不存在");
        }
        if(!dbUser.getPassword().equals(user.getPassword())){
            //密码有误
            throw new ShopException("密码错误");
        }

        return dbUser;

    }

}



